package com.mxfcode.back.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mxfcode.back.dto.RoleDTO;
import com.mxfcode.back.mapper.PermissionMapper;
import com.mxfcode.back.mapper.RoleMapper;
import com.mxfcode.back.service.RoleService;
import com.mxfcode.bbs_common.date.DateUtils;
import com.mxfcode.bbs_common.response.PageDataResult;
import com.mxfcode.common.HostHolder;
import com.mxfcode.entity.TSPermission;
import com.mxfcode.entity.TSRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author moxiufeng
 * @date 2021/3/7 21:17
 */
@Service
public class RoleServiceImpl implements RoleService {
    private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper baseAdminPermission;
    @Autowired
    private HostHolder hostHolder;

    @Override
    public PageDataResult getRoleList(Integer pageNum, Integer pageSize) {
        PageDataResult pageDataResult = new PageDataResult();
        List<TSRole> roles = roleMapper.getRoleList();

        List<RoleDTO> roleList = new ArrayList<>();
        for(TSRole r:roles){
            RoleDTO roleDTO =  new RoleDTO();

            String permissions = r.getPermissions();
            BeanUtils.copyProperties(r,roleDTO);
            roleDTO.setPermissionIds(permissions);

            if(!StringUtils.isEmpty(permissions)){
                String[] ids = permissions.split(",");
                List<String> p = new ArrayList <>();
                for(String id: ids){
                    TSPermission baseAdminPermission = this.baseAdminPermission.selectByPrimaryKey(Integer.valueOf(id));
                    String name = baseAdminPermission.getName();
                    p.add(name);
                }
                roleDTO.setPermissions(p.toString());
            }
            roleList.add(roleDTO);
        }

        PageHelper.startPage(pageNum, pageSize);

        if(roleList.size() != 0){
            PageInfo<RoleDTO> pageInfo = new PageInfo<>(roleList);
            pageDataResult.setList(roleList);
            pageDataResult.setTotals((int) pageInfo.getTotal());
        }
        return pageDataResult;
    }

    @Override
    public Map<String, Object> addRole(TSRole role) {
        Map<String,Object> data = new HashMap();
        try {
            //默认字段
            role.setCreateDate(DateUtils.getCurrentDateToDate());
            role.setCreateBy(hostHolder.getUser().getUserName());
            role.setCreateName(hostHolder.getUser().getRealName());
            role.setUpdateDate(DateUtils.getCurrentDateToDate());
            role.setUpdateBy(hostHolder.getUser().getUserName());
            role.setUpdateName(hostHolder.getUser().getRealName());
            role.setDeleted(1);
            role.setRoleStatus(1);
            int result = roleMapper.insert(role);
            if(result == 0){
                data.put("code",0);
                data.put("msg","新增角色失败");
                logger.error("新增角色失败");
                return data;
            }
            data.put("code",1);
            data.put("msg","新增角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加角色并授权！异常！", e);
        }
        return data;
    }

    @Override
    public Map<String, Object> updateRole(TSRole role) {
        Map<String,Object> data = new HashMap();
        try{
            role.setUpdateName(hostHolder.getUser().getRealName());
            role.setUpdateBy(hostHolder.getUser().getUserName());
            role.setUpdateDate(DateUtils.getCurrentDateToDate());
            int result = roleMapper.updateRole(role);
            if(result == 0){
                data.put("code",0);
                data.put("msg","更新失败！");
                logger.error("角色[更新]，结果=更新失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","更新成功！");
            logger.info("角色[更新]，结果=更新成功！");
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("角色[更新]异常！", e);
            return data;
        }
        return data;
    }

    @Override
    public Map<String, Object> delRole(int id, Integer status) {
        Map<String, Object> data = new HashMap<>();
        try {
            int result = roleMapper.updateRoleStatus(id,status);
            if(result == 0){
                data.put("code",0);
                data.put("msg","删除角色失败");
            }
            data.put("code",1);
            data.put("msg","删除角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除角色异常！", e);
        }
        return data;
    }

    @Override
    public Map<String, Object> recoverRole(int id, Integer status) {
        Map<String, Object> data = new HashMap<>();
        try {
            int result = roleMapper.updateRoleStatus(id,status);
            if(result == 0){
                data.put("code",0);
                data.put("msg","恢复角色失败");
            }
            data.put("code",1);
            data.put("msg","恢复角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("恢复角色异常！", e);
        }
        return data;
    }

    @Override
    public List<TSRole> getRoles() {
        return roleMapper.getRoleList();
    }

}
